<template>
  <div class="param-config-page">
    <el-card shadow="hover">
      <!-- 配置页标题 -->
      <div slot="header" class="page-header">
        <el-button @click="goBack" icon="el-icon-arrow-left" type="text">返回</el-button>
        <h2>工程质量检测参数配置</h2>
      </div>

      <!-- 基础信息配置 -->
      <el-form ref="baseForm" :model="configForm" label-width="120px" class="base-info-form">
        <el-form-item label="检测项目名称" prop="projectName">
          <el-input v-model="configForm.projectName" placeholder="如：钢筋母材及接头力学性能检测"></el-input>
        </el-form-item>
        <el-form-item label="执行标准" prop="standardCode">
          <el-input v-model="configForm.standardCode" placeholder="如：GB/T 228.1-2021"></el-input>
        </el-form-item>
        <el-form-item label="项目编码" prop="projectId">
          <el-input v-model="configForm.projectId" placeholder="如：REBAR001"></el-input>
          <el-button type="text" @click="generateProjectId" style="margin-left: 10px;">自动生成</el-button>
        </el-form-item>
      </el-form>

      <!-- 参数组配置区域 -->
      <div class="param-groups-config">
        <div class="config-toolbar">
          <el-button type="primary" @click="addParamGroup">
            <i class="el-icon-plus"></i> 添加参数组
          </el-button>
          <el-button type="primary" @click="showImportDialog" style="margin-left: 10px;">
            <i class="el-icon-upload2"></i> 导入配置
          </el-button>
          <el-button type="success" @click="saveConfig" style="margin-left: 10px;">
            <i class="el-icon-save"></i> 保存配置
          </el-button>
          <el-button type="info" @click="previewConfig" style="margin-left: 10px;">
            <i class="el-icon-view"></i> 预览配置
          </el-button>
        </div>

        <!-- 动态参数组列表 -->
        <div v-for="(group, groupIndex) in configForm.paramGroups" :key="group.groupId" class="param-group-card">
          <!-- 参数组头部 -->
          <div class="group-header">
            <el-input 
              v-model="group.groupName" 
              placeholder="参数组名称（如：样品基础信息、拉伸试验）" 
              class="group-name-input"
            ></el-input>
            <div class="group-header-actions">
              <el-checkbox 
                v-model="group.isNested" 
                label="嵌套组"
                @change="handleNestedChange(groupIndex)"
              ></el-checkbox>
              <el-checkbox 
                v-model="group.allowDynamicRows" 
                label="动态表格（平行试验）"
                :disabled="group.isNested"
              ></el-checkbox>
              <el-input 
                v-if="group.allowDynamicRows"
                v-model="group.maxRows"
                type="number"
                placeholder="最大行数"
                size="mini"
                class="max-rows-input"
                :min="1"
                @input="group.maxRows = group.maxRows ? Math.max(1, group.maxRows) : 1"
              ></el-input>
              <el-button 
                type="danger" 
                icon="el-icon-delete" 
                size="mini"
                @click="removeParamGroup(groupIndex)"
              ></el-button>
            </div>
          </div>

          <!-- 嵌套组子组配置 -->
          <div v-if="group.isNested" class="nested-groups">
            <div 
              v-for="(childGroup, childIndex) in group.childGroups" 
              :key="childGroup.groupId"
              class="child-group-card"
            >
              <el-input 
                v-model="childGroup.groupName" 
                placeholder="子组名称（如：实测数据、理论计算）" 
                class="child-group-name-input"
              ></el-input>
              <el-button 
                type="text" 
                icon="el-icon-plus" 
                size="mini"
                @click="addParamItem(groupIndex, childIndex, true)"
              >
                添加参数
              </el-button>
              <el-button 
                type="danger" 
                icon="el-icon-delete" 
                size="mini"
                @click="removeChildGroup(groupIndex, childIndex)"
              ></el-button>

              <!-- 子组参数列表 -->
              <el-table 
                :data="childGroup.paramItems" 
                border 
                size="mini"
                class="params-table"
                :loading="tableLoading"
              >
                <el-table-column prop="paramName" label="参数名称" width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.paramName" size="mini" placeholder="如：屈服强度-荷载"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="paramCode" label="参数编码" width="120">
                  <template #default="scope">
                    <el-input v-model="scope.row.paramCode" size="mini" placeholder="如：yieldLoad"></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="dataType" label="数据类型" width="120">
                  <template #default="scope">
                    <el-select 
                      v-model="scope.row.dataType" 
                      size="mini"
                      @change="handleDataTypeChange(scope.row)"
                    >
                      <el-option label="文本" value="text"></el-option>
                      <el-option label="数字" value="number"></el-option>
                      <el-option label="日期" value="date"></el-option>
                      <el-option label="下拉选择" value="select"></el-option>
                      <el-option label="多行文本" value="textarea"></el-option>
                      <el-option label="附件上传" value="attachment"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="unit" label="单位" width="100">
                  <template #default="scope">
                    <el-select v-model="scope.row.unit" size="mini" placeholder="选择/输入单位" allow-create>
                      <el-option label="无" value=""></el-option>
                      <el-option label="mm" value="mm"></el-option>
                      <el-option label="mm²" value="mm²"></el-option>
                      <el-option label="kN" value="kN"></el-option>
                      <el-option label="MPa" value="MPa"></el-option>
                      <el-option label="%" value="%"></el-option>
                      <el-option label="kg" value="kg"></el-option>
                      <el-option label="g" value="g"></el-option>
                      <el-option label="m" value="m"></el-option>
                      <el-option label="mm³" value="mm³"></el-option>
                      <el-option label="kg/m³" value="kg/m³"></el-option>
                      <el-option label="°" value="°"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="paramType" label="参数类型" width="120">
                  <template #default="scope">
                    <el-select v-model="scope.row.paramType" size="mini" @change="handleParamTypeChange(scope.row)">
                      <el-option label="基础参数（手动录入）" value="base"></el-option>
                      <el-option label="计算参数（自动计算）" value="calculation"></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <!-- 多测次配置列 -->
                <el-table-column label="多测次配置" width="120">
                  <template #default="scope">
                    <el-select 
                      v-model="scope.row.multiMeasureCount" 
                      size="mini"
                      placeholder="测次数量"
                      :disabled="scope.row.paramType === 'calculation'"
                    >
                      <el-option label="1次（默认）" value="1"></el-option>
                      <el-option label="2次" value="2"></el-option>
                      <el-option label="3次" value="3"></el-option>
                      <el-option label="4次" value="4"></el-option>
                      <el-option label="5次" value="5"></el-option>
                    </el-select>
                    <el-checkbox 
                      v-model="scope.row.isMultiMeasure" 
                      label="启用"
                      size="mini"
                      :disabled="scope.row.paramType === 'calculation'"
                      class="multi-measure-checkbox"
                    ></el-checkbox>
                  </template>
                </el-table-column>
                <!-- 数字精度列 -->
                <el-table-column label="数字精度" width="100">
                  <template #default="scope">
                    <el-input 
                      v-if="scope.row.dataType === 'number'"
                      v-model="scope.row.precision"
                      type="number"
                      size="mini"
                      placeholder="小数位数"
                      :min="0"
                      @input="scope.row.precision = scope.row.precision ? Math.max(0, scope.row.precision) : 1"
                    ></el-input>
                  </template>
                </el-table-column>
                <!-- 列宽配置列 -->
                <el-table-column label="列宽配置" width="100">
                  <template #default="scope">
                    <el-input 
                      v-model="scope.row.columnWidth"
                      type="number"
                      size="mini"
                      placeholder="列宽(px)"
                      :min="80"
                      :max="300"
                      @input="scope.row.columnWidth = scope.row.columnWidth ? Math.max(80, Math.min(300, scope.row.columnWidth)) : 120"
                    ></el-input>
                  </template>
                </el-table-column>
                <!-- 占位符配置列 -->
                <el-table-column label="输入提示" width="150">
                  <template #default="scope">
                    <el-input 
                      v-model="scope.row.placeholder"
                      size="mini"
                      placeholder="如：请输入检测批次"
                    ></el-input>
                  </template>
                </el-table-column>
                <!-- 依赖参数列 -->
                <el-table-column label="依赖参数" width="180">
                  <template #default="scope">
                    <el-select 
                      v-if="scope.row.paramType === 'calculation'"
                      v-model="scope.row.dependencies"
                      multiple
                      size="mini"
                      placeholder="选择依赖的基础参数"
                      @change="handleDependenciesChange(scope.row)"
                    >
                      <!-- 加载当前组内的所有基础参数 -->
                      <el-option 
                        v-for="baseParam in getBaseParamsByGroup(childGroup, groupIndex, childIndex, true)"
                        :key="baseParam.paramCode"
                        :label="baseParam.paramName"
                        :value="baseParam.paramCode"
                      ></el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <!-- 计算规则列（修复表达式显示） -->
                <el-table-column label="计算规则" width="220">
                  <template #default="scope">
                    <el-button 
                      v-if="scope.row.paramType === 'calculation'"
                      type="text" 
                      size="mini"
                      @click="openCalcRuleDialog(scope.row, groupIndex, childIndex, true)"
                      :class="scope.row.calculationExpr ? 'calc-rule-btn' : 'calc-rule-btn empty'"
                    >
                      {{ scope.row.calculationExpr ? formatCalcExpr(scope.row.calculationExpr) : '点击配置计算规则' }}
                    </el-button>
                  </template>
                </el-table-column>
                <!-- 下拉选项配置列 -->
                <el-table-column label="下拉选项" width="120">
                  <template #default="scope">
                    <el-button 
                      v-if="scope.row.dataType === 'select'"
                      type="text" 
                      size="mini"
                      @click="openSelectOptionsDialog(scope.row)"
                    >
                      配置选项
                    </el-button>
                  </template>
                </el-table-column>
                <!-- 校验规则列 -->
                <el-table-column label="校验规则" width="120">
                  <template #default="scope">
                    <el-button 
                      type="text" 
                      size="mini"
                      @click="openValidateRuleDialog(scope.row)"
                    >
                      配置校验
                    </el-button>
                  </template>
                </el-table-column>
                <!-- 条件显示列 -->
                <el-table-column label="条件显示" width="120">
                  <template #default="scope">
                    <el-button 
                      type="text" 
                      size="mini"
                      @click="openConditionShowDialog(scope.row)"
                    >
                      配置显示
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="scope">
                    <el-button 
                      type="danger" 
                      icon="el-icon-delete" 
                      size="mini"
                      @click="removeParamItem(groupIndex, childIndex, true, scope.$index)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-button 
              type="text" 
              icon="el-icon-plus" 
              size="mini"
              @click="addChildGroup(groupIndex)"
              class="add-child-group-btn"
            >
              添加子组
            </el-button>
          </div>

          <!-- 非嵌套组参数配置 -->
          <div v-else class="normal-group-params">
            <el-button 
              type="text" 
              icon="el-icon-plus" 
              size="mini"
              @click="addParamItem(groupIndex, -1, false)"
            >
              添加参数
            </el-button>
            <el-table 
              :data="group.paramItems" 
              border 
              size="mini"
              class="params-table"
              :loading="tableLoading"
            >
              <el-table-column prop="paramName" label="参数名称" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.paramName" size="mini" placeholder="如：屈服强度-荷载"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="paramCode" label="参数编码" width="120">
                <template #default="scope">
                  <el-input v-model="scope.row.paramCode" size="mini" placeholder="如：yieldLoad"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="dataType" label="数据类型" width="120">
                <template #default="scope">
                  <el-select 
                    v-model="scope.row.dataType" 
                    size="mini"
                    @change="handleDataTypeChange(scope.row)"
                  >
                    <el-option label="文本" value="text"></el-option>
                    <el-option label="数字" value="number"></el-option>
                    <el-option label="日期" value="date"></el-option>
                    <el-option label="下拉选择" value="select"></el-option>
                    <el-option label="多行文本" value="textarea"></el-option>
                    <el-option label="附件上传" value="attachment"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="unit" label="单位" width="100">
                <template #default="scope">
                  <el-select v-model="scope.row.unit" size="mini" placeholder="选择/输入单位" allow-create>
                    <el-option label="无" value=""></el-option>
                    <el-option label="mm" value="mm"></el-option>
                    <el-option label="mm²" value="mm²"></el-option>
                    <el-option label="kN" value="kN"></el-option>
                    <el-option label="MPa" value="MPa"></el-option>
                    <el-option label="%" value="%"></el-option>
                    <el-option label="kg" value="kg"></el-option>
                    <el-option label="g" value="g"></el-option>
                    <el-option label="m" value="m"></el-option>
                    <el-option label="mm³" value="mm³"></el-option>
                    <el-option label="kg/m³" value="kg/m³"></el-option>
                    <el-option label="°" value="°"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="paramType" label="参数类型" width="120">
                <template #default="scope">
                  <el-select v-model="scope.row.paramType" size="mini" @change="handleParamTypeChange(scope.row)">
                    <el-option label="基础参数（手动录入）" value="base"></el-option>
                    <el-option label="计算参数（自动计算）" value="calculation"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <!-- 多测次配置列 -->
              <el-table-column label="多测次配置" width="120">
                <template #default="scope">
                  <el-select 
                    v-model="scope.row.multiMeasureCount" 
                    size="mini"
                    placeholder="测次数量"
                    :disabled="scope.row.paramType === 'calculation'"
                  >
                    <el-option label="1次（默认）" value="1"></el-option>
                    <el-option label="2次" value="2"></el-option>
                    <el-option label="3次" value="3"></el-option>
                    <el-option label="4次" value="4"></el-option>
                    <el-option label="5次" value="5"></el-option>
                  </el-select>
                  <el-checkbox 
                    v-model="scope.row.isMultiMeasure" 
                    label="启用"
                    size="mini"
                    :disabled="scope.row.paramType === 'calculation'"
                    class="multi-measure-checkbox"
                  ></el-checkbox>
                </template>
              </el-table-column>
              <!-- 数字精度列 -->
              <el-table-column label="数字精度" width="100">
                <template #default="scope">
                  <el-input 
                    v-if="scope.row.dataType === 'number'"
                    v-model="scope.row.precision"
                    type="number"
                    size="mini"
                    placeholder="小数位数"
                    :min="0"
                    @input="scope.row.precision = scope.row.precision ? Math.max(0, scope.row.precision) : 1"
                  ></el-input>
                </template>
              </el-table-column>
              <!-- 列宽配置列 -->
              <el-table-column label="列宽配置" width="100">
                <template #default="scope">
                  <el-input 
                    v-model="scope.row.columnWidth"
                    type="number"
                    size="mini"
                    placeholder="列宽(px)"
                    :min="80"
                    :max="300"
                    @input="scope.row.columnWidth = scope.row.columnWidth ? Math.max(80, Math.min(300, scope.row.columnWidth)) : 120"
                  ></el-input>
                </template>
              </el-table-column>
              <!-- 占位符配置列 -->
              <el-table-column label="输入提示" width="150">
                <template #default="scope">
                  <el-input 
                    v-model="scope.row.placeholder"
                    size="mini"
                    placeholder="如：请输入检测批次"
                  ></el-input>
                </template>
              </el-table-column>
              <!-- 依赖参数列 -->
              <el-table-column label="依赖参数" width="180">
                <template #default="scope">
                  <el-select 
                    v-if="scope.row.paramType === 'calculation'"
                    v-model="scope.row.dependencies"
                    multiple
                    size="mini"
                    placeholder="选择依赖的基础参数"
                    @change="handleDependenciesChange(scope.row)"
                  >
                    <!-- 加载当前组内的所有基础参数 -->
                    <el-option 
                      v-for="baseParam in getBaseParamsByGroup(group, groupIndex, -1, false)"
                      :key="baseParam.paramCode"
                      :label="baseParam.paramName"
                      :value="baseParam.paramCode"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <!-- 计算规则列（修复表达式显示） -->
              <el-table-column label="计算规则" width="220">
                <template #default="scope">
                  <el-button 
                    v-if="scope.row.paramType === 'calculation'"
                    type="text" 
                    size="mini"
                    @click="openCalcRuleDialog(scope.row, groupIndex, -1, false)"
                    :class="scope.row.calculationExpr ? 'calc-rule-btn' : 'calc-rule-btn empty'"
                  >
                    {{ scope.row.calculationExpr ? formatCalcExpr(scope.row.calculationExpr) : '点击配置计算规则' }}
                  </el-button>
                </template>
              </el-table-column>
              <!-- 下拉选项配置列 -->
              <el-table-column label="下拉选项" width="120">
                <template #default="scope">
                  <el-button 
                    v-if="scope.row.dataType === 'select'"
                    type="text" 
                    size="mini"
                    @click="openSelectOptionsDialog(scope.row)"
                  >
                    配置选项
                  </el-button>
                </template>
              </el-table-column>
              <!-- 校验规则列 -->
              <el-table-column label="校验规则" width="120">
                <template #default="scope">
                  <el-button 
                    type="text" 
                    size="mini"
                    @click="openValidateRuleDialog(scope.row)"
                  >
                    配置校验
                  </el-button>
                </template>
              </el-table-column>
              <!-- 条件显示列 -->
              <el-table-column label="条件显示" width="120">
                <template #default="scope">
                  <el-button 
                    type="text" 
                    size="mini"
                    @click="openConditionShowDialog(scope.row)"
                  >
                    配置显示
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="80">
                <template #default="scope">
                  <el-button 
                    type="danger" 
                    icon="el-icon-delete" 
                    size="mini"
                    @click="removeParamItem(groupIndex, -1, false, scope.$index)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 下拉选项配置弹窗 -->
    <el-dialog 
      title="配置下拉选项" 
      :visible.sync="selectOptionsDialogVisible"
      width="400px"
    >
      <div class="select-options-container">
        <div 
          v-for="(option, index) in currentSelectOptions" 
          :key="index"
          class="option-item"
        >
          <el-input 
            v-model="option.label" 
            placeholder="选项文本（如：合格）" 
            size="mini"
            class="option-input"
          ></el-input>
          <el-input 
            v-model="option.value" 
            placeholder="选项值（如：合格）" 
            size="mini"
            class="option-input"
          ></el-input>
          <el-button 
            type="danger" 
            icon="el-icon-delete" 
            size="mini"
            @click="removeSelectOption(index)"
          ></el-button>
        </div>
        <el-button 
          type="text" 
          icon="el-icon-plus" 
          size="mini"
          @click="addSelectOption"
          class="add-option-btn"
        >
          添加选项
        </el-button>
      </div>
      <div slot="footer">
        <el-button @click="selectOptionsDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveSelectOptions">确定</el-button>
      </div>
    </el-dialog>

    <!-- 校验规则配置弹窗 -->
    <el-dialog 
      title="配置校验规则" 
      :visible.sync="validateDialogVisible"
      width="400px"
    >
      <el-form :model="currentValidateRule" label-width="100px" class="validate-form">
        <el-form-item label="是否必填">
          <el-switch v-model="currentValidateRule.required" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
        <el-form-item label="必填提示语">
          <el-input 
            v-model="currentValidateRule.requiredMsg" 
            size="mini" 
            placeholder="如：请填写屈服强度荷载"
          ></el-input>
        </el-form-item>
        <!-- 修复：添加 currentParam 空值判断 -->
        <el-form-item label="数值最小值" v-if="currentParam && currentParam.dataType === 'number'">
          <el-input 
            v-model="currentValidateRule.min" 
            type="number" 
            size="mini" 
            placeholder="如：0"
          ></el-input>
        </el-form-item>
        <el-form-item label="数值最大值" v-if="currentParam && currentParam.dataType === 'number'">
          <el-input 
            v-model="currentValidateRule.max" 
            type="number" 
            size="mini" 
            placeholder="如：1000"
          ></el-input>
        </el-form-item>
        <el-form-item label="数值范围提示" v-if="currentParam && currentParam.dataType === 'number'">
          <el-input 
            v-model="currentValidateRule.rangeMsg" 
            size="mini" 
            placeholder="如：荷载需在0-1000kN之间"
          ></el-input>
        </el-form-item>
        <el-form-item label="日期范围" v-if="currentParam && currentParam.dataType === 'date'">
          <el-radio-group v-model="currentValidateRule.dateRangeType">
            <el-radio label="不限制"></el-radio>
            <el-radio label="不晚于当前日期"></el-radio>
            <el-radio label="自定义范围"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="正则表达式" v-if="currentParam && currentParam.dataType === 'text'">
          <el-input 
            v-model="currentValidateRule.regex" 
            size="mini" 
            placeholder="如：^JG-\\d{4}-\\d{3}$"
          ></el-input>
        </el-form-item>
        <el-form-item label="正则提示语" v-if="currentParam && currentParam.dataType === 'text'">
          <el-input 
            v-model="currentValidateRule.regexMsg" 
            size="mini" 
            placeholder="如：样品编号格式为JG-2024-001"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="validateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveValidateRule">确定</el-button>
      </div>
    </el-dialog>

    <!-- 条件显示配置弹窗 -->
    <el-dialog 
      title="配置条件显示规则" 
      :visible.sync="conditionDialogVisible"
      width="450px"
    >
      <el-form :model="currentConditionRule" label-width="120px" class="condition-form">
        <el-form-item label="触发参数">
          <el-select 
            v-model="currentConditionRule.triggerParam" 
            size="mini"
            placeholder="选择触发显示的参数"
          >
            <el-option 
              v-for="param in getAllBaseParams()"
              :key="param.paramCode"
              :label="param.paramName"
              :value="param.paramCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匹配逻辑">
          <el-select v-model="currentConditionRule.matchType" size="mini">
            <el-option label="等于" value="eq"></el-option>
            <el-option label="不等于" value="ne"></el-option>
            <el-option label="包含" value="contain"></el-option>
            <el-option label="不包含" value="notContain"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="触发值">
          <el-input 
            v-model="currentConditionRule.triggerValue" 
            size="mini" 
            placeholder="输入触发显示的值"
          ></el-input>
        </el-form-item>
        <el-form-item label="默认状态">
          <el-select v-model="currentConditionRule.defaultShow" size="mini">
            <el-option label="默认隐藏（满足条件显示）" value="hide"></el-option>
            <el-option label="默认显示（不满足条件隐藏）" value="show"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="conditionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveConditionRule">确定</el-button>
      </div>
    </el-dialog>

    <!-- 配置预览弹窗 -->
    <el-dialog 
      title="参数配置预览（JSON）" 
      :visible.sync="previewDialogVisible"
      width="800px"
      append-to-body
    >
      <el-input 
        v-model="previewJson" 
        type="textarea" 
        rows="20"
        readonly
        class="preview-textarea"
      ></el-input>
      <div slot="footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="copyPreviewJson">复制JSON</el-button>
      </div>
    </el-dialog>

    <!-- 导入配置弹窗 -->
    <el-dialog 
      title="导入参数配置" 
      :visible.sync="importDialogVisible"
      width="60%"
      append-to-body
    >
      <el-form :model="importForm" label-width="80px">
        <el-form-item label="配置JSON">
          <el-input
            v-model="importForm.jsonStr"
            type="textarea"
            :rows="15"
            placeholder="请粘贴完整的参数配置JSON（支持之前导出的配置格式）"
            class="json-input"
          ></el-input>
          <div class="json-tips">
            提示：JSON需包含 projectId、projectName、standardCode、paramGroups 核心字段，参数编码需唯一
          </div>
        </el-form-item>
        <el-form-item label="操作选项">
          <el-radio-group v-model="importForm.coverType">
            <el-radio label="cover">覆盖当前配置</el-radio>
            <el-radio label="merge">合并到当前配置（新增参数组）</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="doImportConfig">确认导入</el-button>
      </div>
    </el-dialog>

    <!-- 计算规则配置弹窗（增强） -->
    <el-dialog 
      title="配置计算规则" 
      :visible.sync="calcRuleDialogVisible"
      width="600px"
      append-to-body
    >
      <el-form :model="currentCalcRule" label-width="100px" class="calc-rule-form">
        <el-form-item label="依赖参数" prop="dependencies">
          <el-select 
            v-model="currentCalcRule.dependencies"
            multiple
            size="mini"
            placeholder="选择计算所需的基础参数"
            @change="handleCalcDependenciesChange"
          >
            <el-option 
              v-for="baseParam in currentGroupBaseParams"
              :key="baseParam.paramCode"
              :label="`${baseParam.paramName}（${baseParam.paramCode}）`"
              :value="baseParam.paramCode"
            ></el-option>
          </el-select>
          <div class="form-tips">提示：仅显示当前参数组内的基础参数</div>
        </el-form-item>
        <!-- 多测次参数访问提示 -->
        <el-form-item label="多测次参数访问" v-if="hasMultiMeasureParams">
          <div class="multi-measure-tips">
            <p>当前依赖的多测次参数访问格式：</p>
            <div v-for="param in multiMeasureDeps" :key="param.paramCode" class="param-access-example">
              {{ param.paramName }}：{{ param.paramCode }}[0].value ~ {{ param.paramCode }}[{{ param.multiMeasureCount - 1 }}].value
            </div>
          </div>
        </el-form-item>
        <el-form-item label="计算表达式" prop="calculationExpr">
          <el-input
            v-model="currentCalcRule.calculationExpr"
            type="textarea"
            :rows="4"
            placeholder="如：ROUND(AVG(length[0].value, length[1].value, length[2].value, length[3].value, length[4].value), 1)"
            class="calc-expr-input"
          ></el-input>
          <div class="form-tips">
            支持语法：<br>
            1. 运算符：+、-、*、/、()（优先级）<br>
            2. 函数：ROUND(数值, 精度)、SUM(参数1,参数2...)、AVG(参数1,参数2...)、MAX()、MIN()、max(数值1,数值2)（避免除以0）<br>
            3. 普通参数：直接使用参数编码（如：mass）<br>
            4. 多测次参数：参数编码[索引].value（如：length[0].value）
          </div>
        </el-form-item>
        <el-form-item label="表达式校验">
          <el-button 
            type="info" 
            size="mini"
            @click="validateCalcExpression"
            :loading="validateLoading"
          >
            <i class="el-icon-check"></i> 校验表达式合法性
          </el-button>
          <div v-if="validateResult" :class="validateSuccess ? 'validate-success' : 'validate-error'">
            {{ validateResult }}
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="calcRuleDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="saveCalcRule"
          :disabled="!validateSuccess && currentCalcRule.calculationExpr.trim()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { generateId } from '@/utils/tool';
import { Message } from 'element-ui';

export default {
  name: 'ParamConfigPage',
  data() {
    return {
      // 配置表单数据（工程检测专用结构）
      configForm: {
        projectId: '',
        projectName: '',
        standardCode: '',
        paramGroups: [] // 参数组列表
      },
      // 表格加载状态
      tableLoading: false,
      // 下拉选项配置弹窗
      selectOptionsDialogVisible: false,
      currentSelectParam: null,
      currentSelectOptions: [],
      // 校验规则配置弹窗
      validateDialogVisible: false,
      currentParam: null, // 初始为null，打开弹窗时赋值
      currentValidateRule: {
        required: false,
        requiredMsg: '',
        min: '',
        max: '',
        rangeMsg: '',
        dateRangeType: '不限制',
        regex: '',
        regexMsg: ''
      },
      // 条件显示配置弹窗
      conditionDialogVisible: false,
      currentConditionRule: {
        triggerParam: '',
        matchType: 'eq',
        triggerValue: '',
        defaultShow: 'hide'
      },
      // 预览弹窗
      previewDialogVisible: false,
      previewJson: '',
      // 导入配置弹窗相关
      importDialogVisible: false,
      importForm: {
        jsonStr: '',
        coverType: 'cover' // cover: 覆盖，merge: 合并
      },
      // 计算规则配置弹窗（增强）
      calcRuleDialogVisible: false,
      currentCalcParam: null, // 当前配置的计算参数
      currentCalcRule: {
        dependencies: [], // 依赖参数编码
        calculationExpr: '' // 计算表达式
      },
      currentGroupBaseParams: [], // 当前参数组的基础参数（用于计算规则依赖选择）
      validateLoading: false, // 表达式校验加载状态
      validateResult: '', // 校验结果提示
      validateSuccess: false, // 校验是否通过
      currentGroupInfo: { // 当前参数组信息（用于多测次参数识别）
        groupIndex: -1,
        childIndex: -1,
        isNested: false
      },
      hasMultiMeasureParams: false, // 是否有依赖的多测次参数
      multiMeasureDeps: [] // 依赖的多测次参数列表
    };
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 自动生成项目编码（前缀+时间戳+随机数）
    generateProjectId() {
      const prefix = 'PROJ';
      const timestamp = new Date().getTime().toString().slice(-6);
      const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
      this.configForm.projectId = `${prefix}${timestamp}${random}`;
    },

    // 显示导入配置弹窗
    showImportDialog() {
      this.importForm.jsonStr = '';
      this.importForm.coverType = 'cover';
      this.importDialogVisible = true;
    },

    // 执行导入配置
    doImportConfig() {
      if (!this.importForm.jsonStr.trim()) {
        Message.error('请粘贴参数配置JSON');
        return;
      }

      try {
        // 解析JSON
        const importConfig = JSON.parse(this.importForm.jsonStr.trim());
        
        // 校验核心字段
        const requiredFields = ['projectId', 'projectName', 'standardCode', 'paramGroups'];
        const missingFields = requiredFields.filter(field => !Object.prototype.hasOwnProperty.call(importConfig, field));
        if (missingFields.length > 0) {
          Message.error(`导入失败：缺少核心字段${missingFields.join('、')}`);
          return;
        }

        // 校验paramGroups格式
        if (!Array.isArray(importConfig.paramGroups)) {
          Message.error('导入失败：paramGroups必须是数组格式');
          return;
        }

        // 校验参数编码唯一性
        const allParamCodes = new Set();
        let hasDuplicateCode = false;
        const traverseParams = (params) => {
          if (!params || !Array.isArray(params)) return;
          params.forEach(param => {
            if (param.paramCode && allParamCodes.has(param.paramCode)) {
              hasDuplicateCode = true;
              return;
            }
            if (param.paramCode) allParamCodes.add(param.paramCode);
          });
        };

        // 遍历所有参数组和子组的参数
        importConfig.paramGroups.forEach(group => {
          traverseParams(group.paramItems);
          if (group.childGroups && Array.isArray(group.childGroups)) {
            group.childGroups.forEach(childGroup => {
              traverseParams(childGroup.paramItems);
            });
          }
        });

        if (hasDuplicateCode) {
          Message.error('导入失败：存在重复的参数编码（paramCode）');
          return;
        }

        // 处理导入逻辑（覆盖或合并）
        if (this.importForm.coverType === 'cover') {
          // 覆盖当前配置
          this.configForm = { 
            ...importConfig,
            // 确保缺失字段有默认值
            paramGroups: importConfig.paramGroups || [],
            projectId: importConfig.projectId || this.generateProjectId()
          };
        } else {
          // 合并配置（新增参数组，保留原有基础信息）
          const newParamGroups = importConfig.paramGroups.filter(newGroup => {
            // 过滤掉与现有组groupId重复的组
            return !this.configForm.paramGroups.some(existGroup => existGroup.groupId === newGroup.groupId);
          });
          this.configForm.paramGroups = [...this.configForm.paramGroups, ...newParamGroups];
          // 合并基础信息（如果导入的信息非空）
          if (importConfig.projectName) this.configForm.projectName = importConfig.projectName;
          if (importConfig.standardCode) this.configForm.standardCode = importConfig.standardCode;
          if (!this.configForm.projectId) this.configForm.projectId = importConfig.projectId || this.generateProjectId();
        }

        Message.success(`导入成功！共${this.configForm.paramGroups.length}个参数组`);
        this.importDialogVisible = false;
      } catch (error) {
        console.error('导入配置解析失败：', error);
        Message.error('导入失败：JSON格式错误或配置不符合要求');
      }
    },

    // 添加参数组
    addParamGroup() {
      this.configForm.paramGroups.push({
        groupId: `GRP${generateId(3)}`,
        groupName: `参数组${this.configForm.paramGroups.length + 1}`,
        isNested: false, // 是否嵌套组
        allowDynamicRows: false, // 是否动态表格（平行试验）
        maxRows: 3, // 动态表格默认最大3行
        childGroups: [], // 子组（嵌套组时用）
        paramItems: [] // 参数项（非嵌套组时用）
      });
    },

    // 移除参数组
    removeParamGroup(index) {
      this.$confirm('确定要删除该参数组吗？删除后不可恢复', '提示', {
        type: 'warning'
      }).then(() => {
        this.configForm.paramGroups.splice(index, 1);
        Message.success('参数组删除成功');
      }).catch(() => {});
    },

    // 嵌套组切换处理
    handleNestedChange(groupIndex) {
      const group = this.configForm.paramGroups[groupIndex];
      if (group.isNested) {
        group.allowDynamicRows = false; // 嵌套组不能是动态表格
        // 初始化子组
        if (group.childGroups.length === 0) {
          this.addChildGroup(groupIndex);
        }
      }
    },

    // 添加子组（嵌套组内）
    addChildGroup(groupIndex) {
      const group = this.configForm.paramGroups[groupIndex];
      group.childGroups.push({
        groupId: `${group.groupId}_${generateId(2)}`,
        groupName: `子组${group.childGroups.length + 1}`,
        paramItems: []
      });
    },

    // 移除子组
    removeChildGroup(groupIndex, childIndex) {
      this.$confirm('确定要删除该子组吗？删除后不可恢复', '提示', {
        type: 'warning'
      }).then(() => {
        this.configForm.paramGroups[groupIndex].childGroups.splice(childIndex, 1);
        Message.success('子组删除成功');
      }).catch(() => {});
    },

    // 添加参数项
    addParamItem(groupIndex, childIndex, isNested) {
      const newParam = {
        paramId: `PARAM${generateId(3)}`,
        paramName: '新参数',
        paramCode: 'param' + Date.now().toString().slice(-4),
        dataType: 'text', // 默认文本类型
        paramType: 'base', // 默认基础参数
        unit: '', // 单位
        isRequired: false,
        calculationExpr: '', // 计算表达式
        dependencies: [], // 依赖参数编码列表
        options: [], // 下拉选项
        validateRule: {}, // 校验规则
        conditionShow: {}, // 条件显示规则
        precision: 1, // 数字精度
        columnWidth: 120, // 表格列宽
        placeholder: '', // 输入提示
        isMultiMeasure: false, // 是否启用多测次
        multiMeasureCount: '1' // 多测次数量（默认1次）
      };

      if (isNested) {
        this.configForm.paramGroups[groupIndex].childGroups[childIndex].paramItems.push(newParam);
      } else {
        this.configForm.paramGroups[groupIndex].paramItems.push(newParam);
      }
    },

    // 移除参数项
    removeParamItem(groupIndex, childIndex, isNested, paramIndex) {
      this.$confirm('确定要删除该参数吗？删除后不可恢复', '提示', {
        type: 'warning'
      }).then(() => {
        if (isNested) {
          this.configForm.paramGroups[groupIndex].childGroups[childIndex].paramItems.splice(paramIndex, 1);
        } else {
          this.configForm.paramGroups[groupIndex].paramItems.splice(paramIndex, 1);
        }
        Message.success('参数删除成功');
      }).catch(() => {});
    },

    // 数据类型变更处理（初始化默认配置）
    handleDataTypeChange(param) {
      // 下拉类型初始化选项
      if (param.dataType === 'select' && !param.options) {
        param.options = [];
      }
      // 数字类型默认精度1位小数
      if (param.dataType === 'number' && param.precision === undefined) {
        param.precision = 1;
      }
      // 附件类型默认配置
      if (param.dataType === 'attachment' && !param.attachmentConfig) {
        param.attachmentConfig = {
          multiple: false, // 默认单文件
          fileType: ['jpg', 'png', 'pdf', 'docx'], // 支持格式
          fileSize: 10 // 最大10MB
        };
      }
    },

    // 参数类型变更处理（切换为计算参数时自动打开配置弹窗）
    handleParamTypeChange(param) {
      if (param.paramType === 'calculation') {
        // 自动切换数据类型为数字
        param.dataType = 'number';
        // 关闭多测次（计算参数不支持多测次）
        param.isMultiMeasure = false;
        // 找到当前参数所在的组信息
        const groupInfo = this.findParamGroupInfo(param);
        // 打开计算规则配置弹窗
        this.openCalcRuleDialog(param, groupInfo.groupIndex, groupInfo.childIndex, groupInfo.isNested);
      } else {
        // 切换为基础参数时清空计算相关配置
        param.calculationExpr = '';
        param.dependencies = [];
      }
    },

    // 查找参数所在的组信息
    findParamGroupInfo(param) {
      for (let groupIndex = 0; groupIndex < this.configForm.paramGroups.length; groupIndex++) {
        const group = this.configForm.paramGroups[groupIndex];
        if (group.isNested) {
          // 嵌套组：遍历子组
          for (let childIndex = 0; childIndex < group.childGroups.length; childIndex++) {
            const childGroup = group.childGroups[childIndex];
            const paramExists = childGroup.paramItems.some(p => p.paramId === param.paramId);
            if (paramExists) {
              return {
                groupIndex,
                childIndex,
                isNested: true
              };
            }
          }
        } else {
          // 非嵌套组
          const paramExists = group.paramItems.some(p => p.paramId === param.paramId);
          if (paramExists) {
            return {
              groupIndex,
              childIndex: -1,
              isNested: false
            };
          }
        }
      }
      return { groupIndex: -1, childIndex: -1, isNested: false };
    },

    // 依赖参数变更处理（确保依赖参数为基础参数）
    handleDependenciesChange(param) {
      // 过滤掉非基础参数的依赖
      const allBaseParams = this.getAllBaseParams().map(p => p.paramCode);
      param.dependencies = param.dependencies.filter(code => allBaseParams.includes(code));
    },

    // 获取当前组内的所有基础参数（用于依赖选择）
    getBaseParamsByGroup(group, groupIndex, childIndex, isNested) {
      let paramItems = [];
      if (isNested) {
        paramItems = group.paramItems || [];
      } else {
        paramItems = group.paramItems || [];
      }
      // 只返回基础参数
      return paramItems.filter(param => param.paramType === 'base');
    },

    // 获取所有基础参数（用于条件显示的触发参数选择）
    getAllBaseParams() {
      let allBaseParams = [];
      // 遍历所有参数组
      this.configForm.paramGroups.forEach(group => {
        if (group.isNested) {
          // 嵌套组遍历子组
          group.childGroups.forEach(childGroup => {
            allBaseParams = [...allBaseParams, ...(childGroup.paramItems || []).filter(p => p.paramType === 'base')];
          });
        } else {
          allBaseParams = [...allBaseParams, ...(group.paramItems || []).filter(p => p.paramType === 'base')];
        }
      });
      return allBaseParams;
    },

    // 打开下拉选项配置弹窗
    openSelectOptionsDialog(param) {
      this.currentSelectParam = param;
      this.currentSelectOptions = JSON.parse(JSON.stringify(param.options || []));
      this.selectOptionsDialogVisible = true;
    },

    // 添加下拉选项
    addSelectOption() {
      this.currentSelectOptions.push({
        label: `选项${this.currentSelectOptions.length + 1}`,
        value: `value${this.currentSelectOptions.length + 1}`
      });
    },

    // 移除下拉选项
    removeSelectOption(index) {
      this.currentSelectOptions.splice(index, 1);
    },

    // 保存下拉选项配置
    saveSelectOptions() {
      if (this.currentSelectParam) {
        this.currentSelectParam.options = this.currentSelectOptions;
        Message.success('下拉选项配置成功');
      }
      this.selectOptionsDialogVisible = false;
    },

    // 打开校验规则配置弹窗
    openValidateRuleDialog(param) {
      this.currentParam = param; // 赋值当前参数，避免null
      // 初始化当前参数的校验规则（无则默认空）
      this.currentValidateRule = JSON.parse(JSON.stringify(param.validateRule || {
        required: false,
        requiredMsg: '',
        min: '',
        max: '',
        rangeMsg: '',
        dateRangeType: '不限制',
        regex: '',
        regexMsg: ''
      }));
      this.validateDialogVisible = true;
    },

    // 保存校验规则配置
    saveValidateRule() {
      if (this.currentParam) {
        this.currentParam.validateRule = this.currentValidateRule;
        Message.success('校验规则配置成功');
      }
      this.validateDialogVisible = false;
      this.currentParam = null; // 关闭弹窗后重置为null，避免残留
    },

    // 打开条件显示配置弹窗
    openConditionShowDialog(param) {
      this.currentParam = param; // 赋值当前参数，避免null
      // 初始化当前参数的条件显示规则
      this.currentConditionRule = JSON.parse(JSON.stringify(param.conditionShow || {
        triggerParam: '',
        matchType: 'eq',
        triggerValue: '',
        defaultShow: 'hide'
      }));
      this.conditionDialogVisible = true;
    },

    // 保存条件显示规则
    saveConditionRule() {
      if (this.currentParam) {
        this.currentParam.conditionShow = this.currentConditionRule;
        Message.success('条件显示规则配置成功');
      }
      this.conditionDialogVisible = false;
      this.currentParam = null; // 关闭弹窗后重置为null，避免残留
    },

    // 预览配置（格式化JSON）
    previewConfig() {
      this.previewJson = JSON.stringify(this.configForm, null, 2);
      this.previewDialogVisible = true;
    },

    // 复制预览JSON
    copyPreviewJson() {
      const textarea = document.createElement('textarea');
      textarea.value = this.previewJson;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('copy');
      document.body.removeChild(textarea);
      Message.success('JSON已复制到剪贴板');
    },

    // 保存配置（模拟接口请求）
    saveConfig() {
      // 表单验证
      if (!this.configForm.projectName) {
        return Message.error('请填写检测项目名称');
      }
      if (!this.configForm.projectId) {
        return Message.error('请填写项目编码');
      }
      if (this.configForm.paramGroups.length === 0) {
        return Message.error('至少添加一个参数组');
      }

      this.tableLoading = true;
      // 模拟后端请求（实际项目替换为axios请求）
      setTimeout(() => {
        // 这里可将this.configForm提交到后端保存
        console.log('最终保存的参数配置：', this.configForm);
        Message.success('参数配置保存成功！');
        this.tableLoading = false;
        // 保存后可跳转到表单预览页或检测列表页
        // this.$router.push({ path: '/test-list' });
      }, 800);
    },

    // ---------------------- 计算规则配置相关方法（增强）----------------------
    // 打开计算规则配置弹窗
    openCalcRuleDialog(param, groupIndex, childIndex, isNested) {
      this.currentCalcParam = param;
      // 记录当前组信息
      this.currentGroupInfo = { groupIndex, childIndex, isNested };
      // 初始化当前参数的计算规则
      this.currentCalcRule = {
        dependencies: [...(param.dependencies || [])],
        calculationExpr: param.calculationExpr || ''
      };
      // 获取当前参数所在组的基础参数（用于依赖选择）
      this.currentGroupBaseParams = this.getBaseParamsOfCurrentGroup(param);
      // 识别依赖的多测次参数
      this.identifyMultiMeasureDeps();
      // 重置校验状态
      this.validateResult = '';
      this.validateSuccess = false;
      // 打开弹窗
      this.calcRuleDialogVisible = true;
    },

    // 获取当前参数所在组的基础参数
    getBaseParamsOfCurrentGroup() {
      const { groupIndex, childIndex, isNested } = this.currentGroupInfo;
      if (groupIndex === -1) return [];

      const group = this.configForm.paramGroups[groupIndex];
      if (isNested) {
        const childGroup = group.childGroups[childIndex];
        return childGroup.paramItems.filter(p => p.paramType === 'base');
      } else {
        return group.paramItems.filter(p => p.paramType === 'base');
      }
    },

    // 识别依赖的多测次参数
    identifyMultiMeasureDeps() {
      const { dependencies } = this.currentCalcRule;
      if (!dependencies.length) {
        this.hasMultiMeasureParams = false;
        this.multiMeasureDeps = [];
        return;
      }

      // 筛选出依赖中启用了多测次的参数
      const multiDeps = this.currentGroupBaseParams.filter(param => 
        dependencies.includes(param.paramCode) && param.isMultiMeasure && param.multiMeasureCount > 1
      );

      this.hasMultiMeasureParams = multiDeps.length > 0;
      this.multiMeasureDeps = multiDeps;
    },

    // 计算规则依赖参数变更处理
    handleCalcDependenciesChange() {
      // 清空校验结果
      this.validateResult = '';
      this.validateSuccess = false;
      // 重新识别多测次参数
      this.identifyMultiMeasureDeps();
    },

    // 格式化计算表达式显示（截取前30个字符）- 修复：删除未使用的param参数
    formatCalcExpr(expr) {
      return expr.length > 30 ? `${expr.slice(0, 30)}...` : expr;
    },

    // 校验计算表达式合法性（支持多测次参数格式）- 修复：不必要的转义字符
    validateCalcExpression() {
      const { calculationExpr, dependencies } = this.currentCalcRule;
      
      if (!calculationExpr.trim()) {
        this.validateResult = '请输入计算表达式';
        this.validateSuccess = false;
        return;
      }

      if (dependencies.length === 0) {
        this.validateResult = '请至少选择一个依赖参数';
        this.validateSuccess = false;
        return;
      }

      this.validateLoading = true;
      try {
        // 1. 替换参数为测试值（处理普通参数和多测次参数）
        let testExpr = calculationExpr;
        
        // 遍历所有依赖参数
        dependencies.forEach(code => {
          const paramItem = this.currentGroupBaseParams.find(p => p.paramCode === code);
          if (paramItem && paramItem.isMultiMeasure && paramItem.multiMeasureCount > 1) {
            // 修复：移除不必要的转义字符 \[ → [
            const regex = new RegExp(`${code}\\[\\d+\\]\\.value`, 'g');
            testExpr = testExpr.replace(regex, '100');
          } else {
            // 普通参数：直接替换参数编码为测试值
            testExpr = testExpr.replace(new RegExp(code, 'g'), '100');
          }
        });

        // 2. 支持的函数映射（新增max函数用于避免除以0）
        const funcMap = {
          ROUND: (num, precision) => Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision),
          SUM: (...args) => args.reduce((a, b) => a + b, 0),
          AVG: (...args) => args.length > 0 ? args.reduce((a, b) => a + b, 0) / args.length : 0,
          MAX: (...args) => Math.max(...args),
          MIN: (...args) => Math.min(...args),
          max: (...args) => Math.max(...args) // 小写max函数，用于避免除以0
        };

        // 3. 执行表达式（使用Function构造器，避免eval的安全问题）
        const result = new Function(...Object.keys(funcMap), `return ${testExpr};`)(...Object.values(funcMap));

        // 4. 校验结果是否为数字
        if (isNaN(result) || !isFinite(result)) {
          throw new Error('表达式计算结果不是有效数字');
        }

        // 校验通过
        this.validateResult = `校验通过！测试计算结果：${result}`;
        this.validateSuccess = true;
      } catch (error) {
        console.error('表达式校验失败：', error);
        this.validateResult = `校验失败：${error.message}`;
        this.validateSuccess = false;
      } finally {
        this.validateLoading = false;
      }
    },

    // 保存计算规则配置
    saveCalcRule() {
      if (!this.currentCalcParam) return;

      // 同步配置到当前参数
      this.currentCalcParam.dependencies = [...this.currentCalcRule.dependencies];
      this.currentCalcParam.calculationExpr = this.currentCalcRule.calculationExpr;

      Message.success('计算规则配置成功');
      this.calcRuleDialogVisible = false;
      this.currentCalcParam = null;
      this.currentGroupInfo = { groupIndex: -1, childIndex: -1, isNested: false };
    }
  }
};
</script>

<style scoped>
.param-config-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}
.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.page-header h2 {
  margin: 0 0 0 15px;
  font-size: 18px;
  font-weight: 700;
}
.base-info-form {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.config-toolbar {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}
.param-group-card {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}
.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
.group-name-input {
  width: 280px;
}
.group-header-actions {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 10px;
}
.max-rows-input {
  width: 80px;
}
.nested-groups {
  padding-left: 25px;
  border-left: 2px dashed #eee;
  margin-top: 10px;
}
.child-group-card {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}
.child-group-name-input {
  width: 220px;
  margin-bottom: 10px;
}
.add-child-group-btn {
  margin-left: 25px;
  color: #409eff;
}
.params-table {
  margin-top: 15px;
  width: 100%;
}
.normal-group-params {
  margin-top: 10px;
}

/* 多测次配置样式 */
.multi-measure-checkbox {
  margin-top: 5px;
  display: block;
}
.multi-measure-tips {
  background-color: #f0f9ff;
  border-radius: 4px;
  padding: 10px;
  margin-top: 5px;
}
.param-access-example {
  font-size: 12px;
  color: #666;
  margin-top: 3px;
}

/* 弹窗样式 */
.select-options-container {
  margin-top: 10px;
}
.option-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
.option-input {
  width: 140px;
}
.add-option-btn {
  margin-top: 5px;
  color: #409eff;
}
.validate-form, .condition-form {
  margin-top: 10px;
}
.validate-form .el-form-item, .condition-form .el-form-item {
  margin-bottom: 15px;
}
.preview-textarea {
  width: 100%;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 14px;
  color: #333;
  background-color: #f5f5f5;
}

/* 导入弹窗样式 */
.json-input {
  width: 100%;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
}
.json-tips {
  margin-top: 10px;
  font-size: 12px;
  color: #666;
}

/* 计算规则配置弹窗样式（增强） */
.calc-rule-form {
  margin-top: 10px;
}
.calc-rule-form .el-form-item {
  margin-bottom: 15px;
}
.calc-expr-input {
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
}
.form-tips {
  margin-top: 5px;
  font-size: 11px;
  color: #666;
  line-height: 1.4;
}
.validate-success {
  margin-top: 8px;
  font-size: 12px;
  color: #67c23a;
}
.validate-error {
  margin-top: 8px;
  font-size: 12px;
  color: #f56c6c;
}
.calc-rule-btn {
  color: #409eff;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  width: 100%;
  text-align: left;
}
.calc-rule-btn.empty {
  color: #909399;
}

/* 响应式调整 */
@media (max-width: 1600px) {
  .params-table {
    font-size: 13px;
  }
  .el-table-column {
    width: auto !important;
    min-width: 100px;
  } 
}

/* 下拉选择允许创建时的样式调整 */
.el-select-dropdown__item.selected {
  background-color: #f0f9ff;
}
.el-select-dropdown__item.create {
  color: #409eff;
}
</style>